package com.newer.SelectorGenerator;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

//TODO  配置文件
public class SelectorGenerator {
	/**输出目录*/
	private static final String OUTPUT_DIR="output/";

	private static final String END_DISABLE = "_dis";
	private static final String END_CLICK = "_clk";
	private static final String END_NORMAL = "_nor";
	

	public static void main(String[] args) {
		File currentDir=new File("./");
		generatSelectorFilesFromDir(currentDir);
	}
	
	/**扫描目录中所有文件,生成selector的xml文件*/
	private static void generatSelectorFilesFromDir(File dir){
		String[] fileNames=dir.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return new File(dir,name).isFile();		//只选择文件
			}
		});
		List<String> fileNameList=Arrays.asList(fileNames);
		HashMap<String,SelectorBean> selectorMap=new HashMap<String,SelectorBean>();
		for (String fileName : fileNameList) {
			String mainFileName=Tools.getMainFileNameFromFileName(fileName);
			if(Tools.isEmpty(mainFileName)){
				continue;
			}
			SelectorBean selector=selectorMap.get(mainFileName);
			if(selector==null){
				selector=new SelectorBean(mainFileName);
				selectorMap.put(mainFileName, selector);
			}
			String fileNameWithOutTypeName=Tools.getFileNameWithOutTypeName(fileName);
			if (fileNameWithOutTypeName.endsWith(END_CLICK)) {
				selector.setClickFileName(fileNameWithOutTypeName);
			} else if (fileNameWithOutTypeName.endsWith(END_DISABLE)) {
				selector.setDiableFileName(fileNameWithOutTypeName);
			} else if (fileNameWithOutTypeName.endsWith(END_NORMAL)) {
				selector.setNormalFileName(fileNameWithOutTypeName);
			}
		}
		
		Collection<SelectorBean> selectorCols = selectorMap.values();
		for (SelectorBean selectorBean : selectorCols) {
			saveFile(selectorBean);
		}
	}
	
	/**保存selector为xml文件*/
	private static boolean saveFile(SelectorBean selector){
		if(selector!=null&&selector.isAvailable()){
			String filePath=OUTPUT_DIR+selector.getMainName()+".xml";
			try {
				return Tools.saveFile(filePath, selector.toXML(),"UTF-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

}
